<?php

namespace quick\admin\actions;

;
use quick\admin\annotation\AdminAuth;
use quick\admin\components\Component;
use quick\admin\http\model\BaseExport;
use quick\admin\http\model\CommonExport;
use quick\admin\http\response\JsonResponse;
use quick\admin\library\queue\job\HandleServiceJob;
use quick\admin\table\Column;

/**
 *  导出
 * @AdminAuth(title="导出",auth=true,login=true,menu=false)
 * @package app\admin\quick\actions
 */
class ExportAction extends RowAction
{

    public $name = "导出";
    public $title = "导出";

    /**
     * 导出类型 download直接下载  queue异步列队下载
     * @var string
     */
    private $exportType = 'download';


    /**
     * @var CommonExport
     */
    private $exportService;


    /**
     * Action constructor.
     * @param string $name
     * @param array $data
     */
    public function __construct(string $btnName = '导出',string $title = '导出')
    {
        $btnName && $this->name = $btnName;
        $title && $this->title = $title;

        $this->request = app()->request;
        $this->init();
    }


    /**
     * 设置导出类
     * @param CommonExport $export
     * @return $this
     */
    public function setExportService(CommonExport $export)
    {
        $this->exportService = $export;
        return $this;
    }


    /**
     * 设置为异步导出类型
     * @return $this
     */
    public function setQueue()
    {
        $this->exportType = 'queue';
        return $this;
    }


    /**
     * 设置为异步导出类型
     * @return $this
     */
    public function setDownload()
    {
        $this->exportType = 'download';
        return $this;
    }

    /**
     * 初始化
     * @return $this
     */
    protected function init()
    {
//        $this->dialog();
        $this->getDisplay()->type("text");
        return $this;
    }



    /**
     * @return $this|void
     * @throws \think\Exception
     */
    protected function initAction()
    {

        $orderExport = $this->getExportService();
        $fieldList = $orderExport->getSelectFields();

        $this->display(Component::custom('export-btn')
            ->style('margin-left','10px')
            ->props([
                'fieldList' => $fieldList,
                'title' => $this->title,
                'btnName' => $this->name,
                'itemWidth' => '130',
                'pageTypes' => ['current','all'],
                'exportUrl' => $this->storeUrl(),
            ])
        );
        return $this;
    }


    public function getExportService():CommonExport
    {
        if(empty($this->exportService)){

            $table =  $this->resource->getTable();
            $model =  $table->getModelQuery();
//            $model =  $query->getThinkModel();


            $export = new BaseExport();
            $export->setDataList($model);
            $columns = $table->getVisibleColumns();

            $fields = [];
            /** @var Column $column */
            foreach($columns as $column){

                if(in_array($column->name,['_key','_actions'])){
                    continue;
                }
                $fields[$column->name] = $column->getTitle();

            }


            $export->setExtraFields($fields);
            $this->exportService = $export;
        }
        return $this->exportService;
    }


    /**
     * @return mixed|JsonResponse
     * @throws \quick\admin\Exceptiona
     */
    public function load()
    {

        if (!$this->handleCanRun($this->request, [])) {
            quick_abort(500, '你无权访问');
        }

        $key = $this->request->get('file');
        $info = cache($key);
        if(empty($info)){
            return $this->response()->error("error");
        }
        return download($info['file'], $info['name'],false,300);

    }







    /**
     * @return mixed|JsonResponse
     * @throws \quick\admin\Exception
     * @throws \think\Exception
     */
    public function store()
    {

        if (!$this->handleCanRun($this->request, [])) {
            quick_abort(500, '你无权访问');
        }


        $fieldsData = $this->request->post('_fields',[]);
        $_pageType = $this->request->post('_pageType');
        $_keyValues_ = $this->request->post('_keyValues_');

        $exportService = $this->getExportService();

        $exportService->disPage = $_pageType == 'all';// 导出全部 或者 一页  select 导出选择数据
        if($_pageType == 'select'){
            if(empty($_keyValues_)){
                return $this->response()->error('请选择导出数据');
            }
            $exportService->setExportIds($_keyValues_);
        }

        $exportService->setFields($fieldsData);
//        $this->exportType = 'queue';

        if($this->exportType == 'download'){
            $filePath = $exportService->exportAction();
            $name = $exportService->getFieldName();
            $key = md5($filePath);
            cache($key,[
                'name' => $name,
                'file' => $filePath,
            ],40);
            return $this->responseDownload($key);
        }else{
            $queueId = $exportService->queueAction();
            return $this->responseQueue($queueId);
        }


    }


    private function responseQueue($queueId)
    {
        return $this->response()->success("success")->event('queue',[$queueId]);
    }



    private function responseDownload(string $key)
    {
        return $this->response()->success("success")
            ->finish([])
            ->download($this->loadUrl(['file' => $key]));
    }

}
